package com.yuanchu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuanchu.auth.dao.YoshopStoreUserDao;
import com.yuanchu.auth.dto.AuthParamsDto;
import com.yuanchu.auth.dto.ShopUserExtend;
import com.yuanchu.auth.entity.YoshopStoreUserEntity;
import com.yuanchu.auth.service.AuthService;
import com.yuanchu.common.exception.YuanChuException;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 账号密码认证
 * @date: 2024-01-15 22:34
 */
@Service("password_authService")
public class PasswordAuthServiceImpl implements AuthService {

    @Resource
    private YoshopStoreUserDao shopUserDao;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    LoadBalancerClient loadBalancerClient;
    @Override
    public ShopUserExtend execute(AuthParamsDto authParamsDto) {
        // 账号
        String username = authParamsDto.getUsername();
        YoshopStoreUserEntity user = shopUserDao.selectOne(new LambdaQueryWrapper<YoshopStoreUserEntity>().eq(YoshopStoreUserEntity::getUserName, username));
        if (user == null) {
            // 返回空表示用户不存在
            throw new YuanChuException("账号不存在");
        }
        // 校验密码
        // 取出数据库存储的正确密码
        String passwordDb = user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches) {
            throw new YuanChuException("账号或密码错误");
        }
        ShopUserExtend shopUserExtend = new ShopUserExtend();
        BeanUtils.copyProperties(user, shopUserExtend);
        return shopUserExtend;
    }




}
